package cn.li.security.json;

import cn.li.security.json.filter.UsernamePasswordJSONAuthenticationFilter;
import cn.li.security.json.handle.AccessDeniedJSONHandler;
import cn.li.security.json.handle.AuthenticationFailJSONHandler;
import cn.li.security.json.handle.AuthenticationSuccessJSONHandler;
import cn.li.security.json.handle.NoneAuthenticationJSONHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class JSONAuthenticationConfiguration extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Setter
    private ObjectMapper objectMapper;
    @Setter
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Setter
    private AuthenticationFailJSONHandler authenticationFailJSONHandler;

    public JSONAuthenticationConfiguration(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
        this.authenticationSuccessHandler =  new AuthenticationSuccessJSONHandler(objectMapper);
        this.authenticationFailJSONHandler =  new AuthenticationFailJSONHandler(objectMapper);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
            UsernamePasswordJSONAuthenticationFilter filter = new UsernamePasswordJSONAuthenticationFilter("/login",this.objectMapper);
            //取得Manager，然后将Filter添加进去
            filter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
            filter.setAuthenticationSuccessHandler(this.authenticationSuccessHandler);
            filter.setAuthenticationFailureHandler(this.authenticationFailJSONHandler);

            http
                .addFilterAfter(filter, UsernamePasswordAuthenticationFilter.class)
        ;
    }

}
